// pages/quiz/quiz.js
const probBase = require("../../utils/probBase.js").probBase

Page({

    /**
     * 页面的初始数据
     */
    data: {
        problems: [],
        curProb: 0,
        selected: [],

        // 随机的题目数量
        n: 4,
        // 正确路径
        corURL: "https://img.icons8.com/color/48/000000/checked.png",
        // 错误路径
        wrongURL: "https://img.icons8.com/color/48/000000/close-window.png",

        showResultDlg: false,
        score: 0,
        isSubmited: false
    },

    onChoiceClicked: function(event) {
        if(this.data.isSubmited) {
            return
        }

        var index = event.currentTarget.dataset["index"]
        var str = "selected[" + this.data.curProb + "]"
        this.setData({
            [str]: index
        });
    },

    prevProb: function() {
        this.setData({
            curProb: this.data.curProb - 1
        })
    },

    nextProb: function() {
        this.setData({
            curProb: this.data.curProb + 1
        })
    },

    onSubmit: function() {
        let s = 0;
        for(let i = 0; i < this.data.problems.length; i++) {
            if(this.data.selected[i] == this.data.problems[i].correctAnswer) {
                s += 10
            }
        }

        this.setData({
            showResultDlg: true,
            score: s
        })
    },

    confirmScore: function() {
        this.setData({
            showResultDlg: false,
            isSubmited: true
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let randomProb = [] //放置抽取过的题目 
        let hash = [] //题目有没有被抽取过 
        for(let i = 0; i < probBase.length; i++) {
            hash.push(false)
        }
        for(let i = 0; i < this.data.n; i++) {
            let rnd = Math.floor(Math.random() * (probBase.length - i)) //表示抽取剩下的题目中的第几题 
            let j = 0; //当前抽到的题
            while(rnd != -1) {
                if(hash[j] == false) {
                    rnd--
                }
                j++
            }
            hash[j - 1] = true
            randomProb.push(probBase[j - 1])
        }
        this.setData({
            problems: randomProb
        })

        var temp = []
        for(let i = 0; i < this.data.problems.length; i++) {
            temp.push(-1)
        }
        this.setData({
            selected: temp
        })
    },
})